package com.zdsoft.blp.gongyong.net;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;

import com.zdsoft.blp.gongyong.dialog.CustomDailog;

public abstract class BaseActivity extends AppCompatActivity {
    private static final int SUCCESS=1;//成功返回数据
    private static final int ERROR=2;//返回数据是空
    private static final int NO_NET=3;//没联网
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        //getActionBar().hide();
        init();
    }

    protected abstract void init();


    public <T extends View> T find(int id){
        return (T)findViewById(id);
    }

    class BaseRunnable implements Runnable{
        private Net net;
        private BaseHanlder hanlder;
        public BaseRunnable(Net net,BaseHanlder hanlder) {
            this.net = net;
            this.hanlder = hanlder;
        }

        @Override
        public void run() {
            Message msg=hanlder.obtainMessage();
            if(WebServiceUtil.isNetworkAvailable(getApplicationContext())){
                String result=WebServiceUtil.getResult(net);
                if("".equals(result)){
                    msg.what=ERROR;
                    msg.obj="返回数据为空";

                }else{
                    msg.what=SUCCESS;
                    msg.obj=result;
                }
            }else{
                msg.what=NO_NET;
                msg.obj="没网";
            }
            Integer resquest=net.code;
            if(resquest!=null){
                msg.arg1=resquest;
            }else{
                msg.arg1=-1;
            }
            hanlder.sendMessage(msg);
        }
    }

    class BaseHanlder extends Handler{
        private NetCallback callback;

        public BaseHanlder(NetCallback callback) {
            this.callback = callback;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SUCCESS:
                    callback.onResponse(true,msg.arg1,msg.obj.toString());
                    break;
                case ERROR:
                    callback.onResponse(false,msg.arg1,msg.obj.toString());
                    break;
                case NO_NET:
                    callback.onResponse(false,msg.arg1,msg.obj.toString());
                    break;
            }
        }
    }


    public  void getServer(Net net,NetCallback callback){
        BaseHanlder hanlder=new BaseHanlder(callback);
        BaseRunnable runnable=new BaseRunnable(net,hanlder);
        //线程池
        ThreadPool.getInstance().addTask(runnable);
    }


}
